// 全局变量
let userInfo = null;
let stompClient = null;
let isMatching = false;
let matchStartTime = null;
let matchTimer = null;
let currentPage = 1;
let totalPages = 1;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

// 初始化页面
async function initializePage() {
    // 检查登录状态
    if (!checkLoginStatus()) {
        return;
    }

    // 加载用户信息
    await loadUserInfo();
    
    // 建立WebSocket连接
    connectWebSocket();
    
    // 加载对局历史
    loadHistory(1);
}

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    const userInfoStr = localStorage.getItem('userInfo');
    
    if (!token || !userInfoStr) {
        window.location.href = 'login.html';
        return false;
    }
    
    try {
        userInfo = JSON.parse(userInfoStr);
        document.getElementById('navUsername').textContent = userInfo.username;
        return true;
    } catch (error) {
        console.error('解析用户信息失败:', error);
        localStorage.clear();
        window.location.href = 'login.html';
        return false;
    }
}

// 加载用户信息
async function loadUserInfo() {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/users/${userInfo.id}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            userInfo = result.data;
            updateUserDisplay();
            // 更新本地存储
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
        } else {
            console.error('加载用户信息失败:', result.message);
        }
    } catch (error) {
        console.error('加载用户信息异常:', error);
    }
}

// 更新用户信息显示
function updateUserDisplay() {
    document.getElementById('username').textContent = userInfo.username;
    document.getElementById('currentScore').textContent = userInfo.currentScore || 0;
    document.getElementById('totalGames').textContent = userInfo.totalGames || 0;
    document.getElementById('winGames').textContent = userInfo.winGames || 0;
    
    const winRate = userInfo.totalGames > 0 
        ? ((userInfo.winGames / userInfo.totalGames) * 100).toFixed(1) 
        : 0;
    document.getElementById('winRate').textContent = winRate + '%';
}

// 建立WebSocket连接
function connectWebSocket() {
    try {
        const token = localStorage.getItem('token');
        const socket = new SockJS('/websocket/gobang');
        stompClient = Stomp.over(socket);
        
        // 设置调试信息
        stompClient.debug = function(str) {
            console.log('STOMP: ' + str);
        };

        const headers = {
            'Authorization': `Bearer ${token}`
        };

        stompClient.connect(headers, function(frame) {
            console.log('WebSocket连接成功: ' + frame);
            updateConnectionStatus(true);
            
            // 订阅用户消息
            stompClient.subscribe(`/user/queue/messages`, function(message) {
                handleWebSocketMessage(JSON.parse(message.body));
            });
            
        }, function(error) {
            console.error('WebSocket连接失败: ', error);
            updateConnectionStatus(false);
            // 尝试重连
            setTimeout(connectWebSocket, 5000);
        });
    } catch (error) {
        console.error('WebSocket连接异常:', error);
        updateConnectionStatus(false);
    }
}

// 更新连接状态显示
function updateConnectionStatus(connected) {
    const statusEl = document.getElementById('connectionStatus');
    const textEl = document.getElementById('connectionText');
    const loadingEl = document.getElementById('connectionLoading');
    
    if (connected) {
        statusEl.className = 'status-message status-success';
        textEl.textContent = '✓ 已连接';
        loadingEl.style.display = 'none';
    } else {
        statusEl.className = 'status-message status-warning';
        textEl.textContent = '⚠ 连接中断';
        loadingEl.style.display = 'inline-block';
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(message) {
    console.log('收到WebSocket消息:', message);
    
    switch (message.type) {
        case 'HEARTBEAT':
            // 响应心跳
            sendHeartbeatResponse();
            break;
            
        case 'MATCH_STATUS_UPDATE':
            updateMatchStatus(message.data);
            break;
            
        case 'MATCH_SUCCESS':
            handleMatchSuccess(message.data);
            break;
            
        case 'ERROR_RESPONSE':
            handleErrorMessage(message.data);
            break;
            
        default:
            console.log('未处理的消息类型:', message.type);
    }
}

// 发送心跳响应
function sendHeartbeatResponse() {
    if (stompClient && stompClient.connected) {
        stompClient.send('/app/heartbeat', {}, JSON.stringify({
            type: 'HEARTBEAT_RESPONSE',
            data: {
                timestamp: Date.now()
            }
        }));
    }
}

// 切换匹配状态
async function toggleMatching() {
    if (isMatching) {
        await cancelMatching();
    } else {
        await startMatching();
    }
}

// 开始匹配
async function startMatching() {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/match/join', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userInfo.id
            })
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            isMatching = true;
            matchStartTime = Date.now();
            updateMatchingUI(true);
            startMatchTimer();
            
            // 更新队列信息
            if (result.data) {
                document.getElementById('queuePosition').textContent = result.data.queuePosition || '-';
                document.getElementById('estimatedTime').textContent = result.data.estimatedWaitTime || '-';
            }
        } else {
            handleMatchError(result.code, result.message);
        }
    } catch (error) {
        console.error('开始匹配失败:', error);
        showMessage('网络连接失败，请重试', 'error');
    }
}

// 取消匹配
async function cancelMatching() {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch('/api/match/cancel', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userInfo.id
            })
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            isMatching = false;
            updateMatchingUI(false);
            stopMatchTimer();
        } else {
            console.error('取消匹配失败:', result.message);
        }
    } catch (error) {
        console.error('取消匹配异常:', error);
    }
}

// 更新匹配UI
function updateMatchingUI(matching) {
    const matchBtn = document.getElementById('matchBtn');
    const matchBtnText = document.getElementById('matchBtnText');
    const matchingStatus = document.getElementById('matchingStatus');
    
    if (matching) {
        matchBtn.classList.add('matching');
        matchBtnText.textContent = '取消匹配';
        matchingStatus.style.display = 'block';
    } else {
        matchBtn.classList.remove('matching');
        matchBtnText.textContent = '开始匹配';
        matchingStatus.style.display = 'none';
    }
}

// 开始匹配计时器
function startMatchTimer() {
    matchTimer = setInterval(() => {
        if (matchStartTime) {
            const elapsed = Math.floor((Date.now() - matchStartTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            document.getElementById('matchTimer').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    }, 1000);
}

// 停止匹配计时器
function stopMatchTimer() {
    if (matchTimer) {
        clearInterval(matchTimer);
        matchTimer = null;
    }
    matchStartTime = null;
    document.getElementById('matchTimer').textContent = '00:00';
}

// 更新匹配状态
function updateMatchStatus(data) {
    if (data.queuePosition) {
        document.getElementById('queuePosition').textContent = data.queuePosition;
    }
    if (data.waitTime) {
        document.getElementById('estimatedTime').textContent = data.waitTime;
    }
}

// 处理匹配成功
function handleMatchSuccess(data) {
    console.log('匹配成功:', data);
    isMatching = false;
    stopMatchTimer();
    
    showMessage(`匹配成功！对手：${data.opponent.username}，正在进入游戏...`, 'success');
    
    // 延迟跳转到游戏页面
    setTimeout(() => {
        window.location.href = `game.html?roomId=${data.roomId}`;
    }, 2000);
}

// 处理匹配错误
function handleMatchError(code, message) {
    let errorMsg = message;
    switch (code) {
        case '5001':
            errorMsg = '您已在匹配队列中';
            break;
        case '5002':
            errorMsg = '您正在游戏中';
            break;
        default:
            errorMsg = message || '匹配失败，请重试';
    }
    showMessage(errorMsg, 'error');
}

// 处理错误消息
function handleErrorMessage(data) {
    console.error('WebSocket错误:', data);
    showMessage(data.errorMessage || '发生错误', 'error');
}

// 加载对局历史
async function loadHistory(page) {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/scores/records/${userInfo.id}?current=${page}&size=10`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        const result = await response.json();
        
        if (result.code === '1000') {
            displayHistory(result.data);
        } else {
            console.error('加载对局历史失败:', result.message);
            displayHistoryError();
        }
    } catch (error) {
        console.error('加载对局历史异常:', error);
        displayHistoryError();
    }
}

// 显示对局历史
function displayHistory(data) {
    const historyList = document.getElementById('historyList');
    const pagination = document.getElementById('pagination');
    
    if (!data.records || data.records.length === 0) {
        historyList.innerHTML = '<div class="text-center" style="padding: 20px; color: #7f8c8d;">暂无对局历史</div>';
        pagination.style.display = 'none';
        return;
    }
    
    let html = '';
    data.records.forEach(record => {
        const resultClass = record.gameResult === 'WIN' ? 'win' : 'lose';
        const resultText = record.gameResult === 'WIN' ? '胜利' : '失败';
        const scoreClass = record.scoreChange > 0 ? 'score-positive' : 'score-negative';
        const scoreText = record.scoreChange > 0 ? `+${record.scoreChange}` : record.scoreChange;
        
        html += `
            <div class="history-item">
                <div class="history-date">${formatDate(record.gameTime)}</div>
                <div class="history-opponent">对手：${record.opponentUsername}</div>
                <div class="history-result">
                    <span class="${resultClass}">${resultText}</span>
                    <span class="score-change ${scoreClass}">${scoreText}分</span>
                </div>
            </div>
        `;
    });
    
    historyList.innerHTML = html;
    
    // 更新分页
    currentPage = data.current || 1;
    totalPages = data.pages || 1;
    document.getElementById('pageInfo').textContent = `${currentPage} / ${totalPages}`;
    document.getElementById('prevPage').disabled = currentPage <= 1;
    document.getElementById('nextPage').disabled = currentPage >= totalPages;
    pagination.style.display = 'flex';
}

// 显示历史加载错误
function displayHistoryError() {
    const historyList = document.getElementById('historyList');
    historyList.innerHTML = '<div class="text-center" style="padding: 20px; color: #E74C3C;">加载失败，请刷新重试</div>';
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = now - date;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
        return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays === 1) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else {
        return date.toLocaleDateString('zh-CN');
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageEl = document.getElementById('matchMessage');
    messageEl.className = `status-message status-${type}`;
    messageEl.textContent = message;
    messageEl.style.display = 'block';
    
    // 3秒后自动隐藏
    setTimeout(() => {
        messageEl.style.display = 'none';
    }, 3000);
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        // 断开WebSocket连接
        if (stompClient && stompClient.connected) {
            stompClient.disconnect();
        }
        
        // 清除本地存储
        localStorage.clear();
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    }
}

// 页面卸载时清理资源
window.addEventListener('beforeunload', function() {
    if (stompClient && stompClient.connected) {
        stompClient.disconnect();
    }
    if (matchTimer) {
        clearInterval(matchTimer);
    }
}); 